package com.fafa.event;

import javax.swing.*;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * 通过键盘控制小球移动
 */
public class BallMove extends JFrame {
    MyPanel mp = null;

    public static void main(String[] args) {
        BallMove ballMove = new BallMove();

    }

    public BallMove() {
        mp = new MyPanel();
        this.add(mp);
        this.setSize(400, 300);
        //放入一个KeyListener接口的对象 接口的引用可以放入一个实现了该接口的对象
        this.addKeyListener(mp); //告诉程序有监听键盘事件
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
}

//KeyListener是监听器，可以监听键盘事件
class MyPanel extends JPanel implements KeyListener {
    int x = 10;
    int y = 10;
    int speed = 5;

    @Override
    public void paint(Graphics g) {

        super.paint(g);
        g.fillOval(x, y, 20, 20);
    }

    //字符输出时
    @Override
    public void keyTyped(KeyEvent e) {

    }

    //按下某个键时
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        switch (keyCode) {
            case KeyEvent.VK_UP:
                //System.out.println("上");
                y -= speed;
                break;
            case KeyEvent.VK_DOWN:
                //System.out.println("下");
                y += speed;
                break;
            case KeyEvent.VK_LEFT:
                //System.out.println("左");
                x -= speed;
                break;
            case KeyEvent.VK_RIGHT:
                //System.out.println("右");
                x += speed;
                break;
            default:
                break;
        }
        this.repaint();

    }

    //松开某个键时
    @Override
    public void keyReleased(KeyEvent e) {

    }
}
